package com.rdc.example.dao.impl;

import com.rdc.example.dao.UserDao;
import com.rdc.example.entity.User;
import com.rdc.example.util.DBUtil;
import com.rdc.example.util.HashUtil;

import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

import static com.rdc.example.util.DBUtil.closeResources;
import static com.rdc.example.util.DBUtil.getConnection;

/**
 * @author duck
 * @description User实体类dao层接口实现类
 */
public class UserDaoImpl implements UserDao {

    public static void main(String[] args) throws Exception {
        UserDaoImpl userDao = new UserDaoImpl();
        User user = new User();
        //System.out.println(userDao.getUserByName("路人甲"));

        System.out.println(userDao.getUserById(6));
    }
    /**
     * 登录验证用户名和密码并返回结果
     * @param userName 用户名称
     * @param password 用户明文密码
     * @return 登录结果
     * */
    @Override
    public boolean login(String userName, String password) throws Exception {
        //只能传入密码原值，在与数据库中的加密值比较
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try {
            conn = getConnection();
            String sql = "select password_hash from user where user_name=?" ;
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userName);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                return HashUtil.getSaltverifyMD5(password,rs.getString("password_hash"));
            }
            else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
            closeResources(rs, pstmt, conn);
        }
    }

    /**
     * 注册用户
     * @param user 用户类
     * @return 注册结果
     * */
    @Override
    public boolean insert(User user) throws Exception {
        // 进行数据库插入操作
        Connection conn =null;
        PreparedStatement pstmt=null;
        try {
            conn = getConnection();
            String sql ="INSERT INTO user (user_name, email, password_hash,status,power) VALUES (?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUserName());
            pstmt.setString(2, user.getEmail());
            pstmt.setString(3, user.getPasswordHash());
            pstmt.setInt(4, 1);
            if(user.getPower()!=null){
                pstmt.setInt(5, user.getPower());
            }else{
                pstmt.setInt(5, 0);
            }
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLIntegrityConstraintViolationException e) {
            System.out.println("用户名已存在： "+user.getUserName());
            return false;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(null,pstmt,conn);
        }
    }

    /**
     * 通过id删除用户
     * @param id 用户id
     * @return 删除结果
     * */
    @Override
    public boolean deleteById(Integer id) throws Exception {
        // 进行数据库删除操作
        Connection conn =null;
        PreparedStatement pstmt=null;
        //ResultSet rs=null;
        try {
            conn = getConnection();
            String sql = "delete from user where id=?" ;
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, id);
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLIntegrityConstraintViolationException e) {
            e.printStackTrace();
        }finally {
            closeResources(null,pstmt,conn);
        }
        return false;
    }

    /**
     * 通过id更新用户信息
     * @param user 用户类
     * @return 更新结果
     * */
    @Override
    public boolean updateById(User user) throws Exception {
        // 进行数据库更新操作
        Connection conn =null;
        PreparedStatement pstmt=null;
        try {
            conn = getConnection();
            String sql = "update user set user_name=?, email=?, password_hash=?, status=? where id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUserName());
            //email可为空
            if (user.getEmail() != null) {
                pstmt.setString(2, user.getEmail());
            } else {
                pstmt.setNull(2, Types.VARCHAR);
            }
            pstmt.setString(3, user.getPasswordHash());
            //status可不插入
            if (user.getStatus() != null) {
                pstmt.setInt(4, user.getStatus());
            } else {
                pstmt.setNull(4, 1);
            }
            pstmt.setInt(5, user.getId());
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLIntegrityConstraintViolationException e) {
            System.out.println("用户名已存在： "+user.getUserName());
            return false;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(null,pstmt,conn);
        }
    }

    /**
     * 通过用户名称获取用户信息
     * @param userName 用户名称
     * @return user类
     * */
    @Override
    public User getUserByName(String userName) throws Exception {
        // 进行数据库查询操作
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs = null;
        User user = null;
        try{
            conn=getConnection();
            String sql = "select * from user where user_name=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userName);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                user = getUser(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            closeResources(rs,pstmt,conn);
        }
        return user;
    }

    /**
     * 通过用户名称获取用户信息
     * @param id 用户id
     * @return user类
     * */
    @Override
    public User getUserById(Integer id) throws Exception {
        // 进行数据库查询操作
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs = null;
        User user = null;
        try{
            conn=getConnection();
            String sql = "select * from user where id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                user = getUser(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            closeResources(rs,pstmt,conn);
        }
        return user;
    }

    /**
     * 获取所有用户信息
     * @return userList
     * */
    @Override
    public List<User> listUser() throws Exception {
        // 进行数据库查询操作
        Connection conn = getConnection();
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        List<User> userList = new ArrayList<>();
        User user = null;
        try {
            String sql = "select * from user";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                user = getUser(rs);
                userList.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            closeResources(rs, pstmt, conn);
        }
        return userList;
    }

    public List<User> searchUsersByName(String keyword) throws Exception {
        List<User> userList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;
        try {
            conn = getConnection();
            String sql = "select * from user where user_name like ?";
            pstmt = conn.prepareStatement(sql);
            // 设置参数：添加 % 通配符（如 "%john%")
            pstmt.setString(1, "%" + keyword + "%");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                user = getUser(rs);
                userList.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResources(rs, pstmt, conn);
        }
        return userList;
    }

    @Override
    public Map<Integer, User> getUsersByIds(Set<Integer> userIds) {
        Map<Integer, User> userMap = new HashMap<>();
        if (userIds == null || userIds.isEmpty()) {
            return userMap;
        }
        String sql = "SELECT id, user_name FROM user WHERE id IN (" +
                userIds.stream().map(String::valueOf).collect(Collectors.joining(",")) + ")";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("user_name"));
                userMap.put(user.getId(), user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return userMap;
    }


    private User getUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUserName(rs.getString("user_name"));
        user.setEmail(rs.getString("email"));
        user.setPasswordHash(rs.getString("password_hash"));
        user.setStatus(rs.getInt("status"));
        user.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
        user.setPower(rs.getInt("power"));
        return user;
    }
}
